<template>
<div id="app">
    <Login v-if="!isLoggedIn" @login="login" />
    <template v-else>
      <el-drawer v-model="drawerVisible" direction="ltr" :with-header="false" size="220px" class="mobile-drawer">
        <div class="dev-info" style="padding: 20px 20px 8px 20px; border-bottom: 1px solid rgba(255,255,255,0.1);">
          <div class="project-title"><span class="project-title-main">冀滦纸业品技部</span><br /><span class="project-title-sub">综合办公系统</span></div>
          <!-- 顶部模式显示修正 -->
          <p v-if="isGuestMode" class="user-role-label" style="color: #ffa500; font-size: 12px;">访客模式</p>
          <p v-else class="user-role-label" style="color: #67c23a; font-size: 12px;">{{ userRoleLabel }}：{{ currentUsername }}</p>
        </div>
        <el-menu :default-active="activeMenu" @select="handleMenuSelect">
          <el-menu-item index="dashboard"><span>仪表盘</span></el-menu-item>
          <el-menu-item index="devices"><span>设备管理</span></el-menu-item>
          <el-menu-item index="repair"><span>维修记录</span></el-menu-item>
          <el-menu-item index="spareparts"><span>备件管理</span></el-menu-item>
          <el-menu-item index="standard-maintain"><span>成品技术标准</span></el-menu-item>
          <el-menu-item index="factory-report"><span>出厂报告管理</span></el-menu-item>
          <el-menu-item index="document-manage"><span>文档管理</span></el-menu-item>
          <el-menu-item index="qrcode"><span>二维码管理</span></el-menu-item>
          <el-menu-item v-if="userRole === 'admin' || userRole === 'superadmin'" index="user-manage"><span>用户管理</span></el-menu-item>
        </el-menu>
        <div class="logout-section">
          <el-button link @click="logout" style="color: #fff; width: 100%; text-align: left; padding: 12px 20px;">退出登录</el-button>
        </div>
        <div class="dev-info" style="margin-top:auto; padding: 16px 20px 8px 20px; font-size: 12px; color: #b0b8c9; text-align: left;">
          Developer: Yao Junlei<br />
          Platform: Cursor & LeanCloud<br />
          Version {{ appVersion }}-beta 测试版
        </div>
      </el-drawer>
      <div v-if="isMobile" class="mobile-header">
        <el-button circle size="large" @click="drawerVisible = true" style="margin-right: 8px; background: #1677ff; color: #fff; border: none; box-shadow: 0 2px 8px rgba(22,119,255,0.12);">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect y="4" width="24" height="2" rx="1" fill="currentColor"/>
            <rect y="11" width="24" height="2" rx="1" fill="currentColor"/>
            <rect y="18" width="24" height="2" rx="1" fill="currentColor"/>
          </svg>
        </el-button>
        <span class="mobile-title">冀滦纸业品技部综合办公系统</span>
      </div>
      <div v-else class="app-container">
        <div class="sidebar">
          <div class="dev-info" style="padding: 20px 20px 8px 20px; border-bottom: 1px solid rgba(255,255,255,0.1);">
            <div class="project-title"><span class="project-title-main">冀滦纸业品技部</span><br /><span class="project-title-sub">综合办公系统</span></div>
            <!-- 顶部模式显示修正 -->
            <p v-if="isGuestMode" class="user-role-label" style="color: #ffa500; font-size: 12px;">访客模式</p>
            <p v-else class="user-role-label" style="color: #67c23a; font-size: 12px;">{{ userRoleLabel }}：{{ currentUsername }}</p>
          </div>
          <el-menu :default-active="activeMenu" @select="handleMenuSelect">
            <el-menu-item index="dashboard">
              <span>仪表盘</span>
            </el-menu-item>
            <el-menu-item index="devices">
              <span>设备管理</span>
            </el-menu-item>
            <el-menu-item index="repair">
              <span>维修记录</span>
            </el-menu-item>
            <el-menu-item index="spareparts">
              <span>备件管理</span>
            </el-menu-item>
            <el-menu-item index="standard-maintain">
              <span>成品技术标准</span>
            </el-menu-item>
            <el-menu-item index="factory-report">
              <span>出厂报告管理</span>
            </el-menu-item>
            <el-menu-item index="document-manage">
              <span>文档管理</span>
            </el-menu-item>
            <el-menu-item index="qrcode">
              <span>二维码管理</span>
            </el-menu-item>
            <el-menu-item v-if="userRole === 'admin' || userRole === 'superadmin'" index="user-manage">
              <span>用户管理</span>
            </el-menu-item>
          </el-menu>
          <div class="logout-section">
            <el-button link @click="logout" style="color: #fff; width: 100%; text-align: left; padding: 12px 20px;">
              退出登录
            </el-button>
          </div>
          <div class="dev-info" style="margin-top:auto; padding: 16px 20px 8px 20px; font-size: 12px; color: #b0b8c9; text-align: left;">
            Developer: Yao Junlei<br />
            Platform: Cursor & LeanCloud<br />
            Version {{ appVersion }}-beta 测试版
          </div>
        </div>
        <div class="main-content">
          <router-view />
        </div>
      </div>
      <div v-if="isMobile" class="main-content mobile-main">
        <router-view />
      </div>
    </template>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, provide, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import Dashboard from './components/Dashboard.vue'
import DeviceList from './components/DeviceList.vue'
import Repair from './components/Repair.vue'
import QRCodeManage from './components/QRCodeManage.vue'
import SpareParts from './components/SpareParts.vue'
import Login from './components/Login.vue'
import FactoryReport from './components/FactoryReport.vue'
import AV from './leancloud'

// 新增：同步UserProfile函数
async function syncUserProfile() {
  const user = AV.User.current();
  if (!user) return null;
  const query = new AV.Query('UserProfile');
  query.equalTo('username', user.getUsername());
  let profile = await query.first();
  if (!profile) {
    // 新建UserProfile，默认普通用户
    profile = new AV.Object('UserProfile');
    profile.set('username', user.getUsername());
    profile.set('role', 'user');
    profile.set('isActive', true);
    profile.set('needChangePwd', false);
    // 设置ACL
    const acl = new AV.ACL();
    acl.setPublicReadAccess(true);
    acl.setPublicWriteAccess(false);
    acl.setRoleWriteAccess('admin', true);
    profile.setACL(acl);
    await profile.save();
  } else {
    // 已存在用户档案
  }
  return profile;
}

export default {
  name: 'App',
  components: {
    Dashboard,
    DeviceList,
    Repair,
    QRCodeManage,
    SpareParts,
    Login,
    FactoryReport // 注册出厂报告管理组件
  },
  setup() {
    const isLoggedIn = ref(false)
    const isGuestMode = ref(false)
    const showAdminLogin = ref(false)
    const password = ref('')
    const activeMenu = ref('dashboard')
    const currentDeviceId = ref(null)
    const drawerVisible = ref(false)
    const isMobile = ref(window.innerWidth <= 700)
    const router = useRouter()
    const route = useRoute()
    // 只在login成功后赋值userRole，页面其它地方只读localStorage
    const userRole = ref(localStorage.getItem('userRole') || 'user')
    const currentUsername = ref(localStorage.getItem('currentUsername') || '未知用户')
    watch(userRole, () => {
      currentUsername.value = localStorage.getItem('currentUsername') || '未知用户'
    })
    const userRoleLabel = computed(() => {
      if (isGuestMode.value) return '访客'
      if (userRole.value === 'superadmin') return '超级管理员'
      if (userRole.value === 'admin') return '管理员'
      return '普通用户'
    })
    const appVersion = __APP_VERSION__

    provide('showLogin', () => { isLoggedIn.value = false })

    function handleResize() {
      isMobile.value = window.innerWidth <= 700
    }

    function updateActiveMenu(route) {
      if (route.path.startsWith('/spareparts')) {
        activeMenu.value = 'spareparts'
      } else if (route.path.startsWith('/device-list')) { // 修正这里
        activeMenu.value = 'devices'
      } else if (route.path.startsWith('/device-detail')) {
        activeMenu.value = 'devices'
      } else if (route.path.startsWith('/repair')) {
        activeMenu.value = 'repair'
      } else if (route.path.startsWith('/qrcode')) {
        activeMenu.value = 'qrcode'
      } else if (route.path.startsWith('/user-manage')) {
        activeMenu.value = 'user-manage'
      } else if (route.path.startsWith('/factory-report')) {
        activeMenu.value = 'factory-report'
      } else if (route.path.startsWith('/document-manage')) {
        activeMenu.value = 'document-manage'
      } else if (route.path.startsWith('/standard-maintain')) {
        activeMenu.value = 'standard-maintain'
      } else if (route.path.startsWith('/version-viewer')) {
        activeMenu.value = 'version-viewer'
      } else {
        activeMenu.value = 'dashboard'
      }
    }
    
    const currentComponent = computed(() => {
      const components = {
        dashboard: Dashboard,
        devices: DeviceList,
        repair: Repair,
        qrcode: QRCodeManage,
        spareparts: SpareParts,
        'factory-report': FactoryReport, // 新增出厂报告管理组件
      }
      return components[activeMenu.value] || Dashboard
    })
    
    // 只在login成功后赋值userRole
    const login = async ({ isGuest }) => {
      if (isGuest) {
        isLoggedIn.value = true
        isGuestMode.value = true
        userRole.value = 'guest'
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('isGuestMode', 'true')
        localStorage.setItem('userRole', 'guest')
        localStorage.setItem('currentUsername', '访客')
        // 登录后跳转回原页面
        let redirect = localStorage.getItem('loginRedirect')
        if (redirect) {
          router.replace(redirect)
          localStorage.removeItem('loginRedirect')
        } else {
          router.push('/dashboard')
        }
      } else {
        isLoggedIn.value = true
        isGuestMode.value = false
        try {
          let user = AV.User.current()
          if (user) await user.fetch()
          // 新增：同步UserProfile
          const profile = await syncUserProfile();
          const role = profile?.get('role') || 'user';
          userRole.value = role;
          localStorage.setItem('userRole', role);
          // 存储当前用户名
          let username = user?.getUsername() || profile?.get('username') || '未知用户'
          localStorage.setItem('currentUsername', username)
          // 如果被禁用，强制登出
          const isActive = profile?.get('isActive') !== false;
          if (!isActive) {
            ElMessage.error('账号已被禁用，请联系管理员')
            isLoggedIn.value = false
            localStorage.removeItem('isLoggedIn')
            localStorage.setItem('isGuestMode', 'true')
            return
          }
          // 登录成功后强制刷新，确保所有组件拿到最新权限（不影响微信内置浏览器多次浏览）
          if (!/MicroMessenger/i.test(navigator.userAgent)) {
            window.location.reload()
          }
        } catch (e) {
          userRole.value = 'user'
          localStorage.setItem('userRole', 'user')
          localStorage.setItem('currentUsername', '未知用户')
        }
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('isGuestMode', 'false')
        // 登录后跳转回原页面
        let redirect = localStorage.getItem('loginRedirect')
        if (redirect) {
          router.replace(redirect)
          localStorage.removeItem('loginRedirect')
        } else {
          router.push('/dashboard')
        }
      }
    }
    
    const loginAsGuest = () => {
      isLoggedIn.value = true
      isGuestMode.value = true
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('isGuestMode', 'true')
    }
    
    const logout = () => {
      isLoggedIn.value = false
      isGuestMode.value = true
      // 清理所有用户相关localStorage字段
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('isGuestMode')
      localStorage.removeItem('userRole')
      localStorage.removeItem('currentUsername')
      localStorage.removeItem('sessionToken')
      activeMenu.value = 'dashboard'
    }
    
    const handleMenuSelect = (index) => {
      const map = {
        dashboard: '/dashboard',
        devices: '/device-list',
        repair: '/repair',
        qrcode: '/qrcode',
        spareparts: '/spareparts',
        'user-manage': '/user-manage',
        'factory-report': '/factory-report', // 新增出厂报告管理路由
        'standard-maintain': '/standard-maintain', // 新增技术标准路由
        'document-manage': '/document-manage' // 新增文档管理路由
      }
      const targetPath = map[index] || '/dashboard'
      router.push(targetPath)
      activeMenu.value = index
    }
    
    // 修改goDetail逻辑
    function goDetail(device) {
      activeMenu.value = 'device-detail'
      currentDeviceId.value = device.objectId // 确保是objectId
    }

    function handleDeviceBack() {
      activeMenu.value = 'spareparts'
      currentDeviceId.value = null
    }

    function handleDeviceBackDevices() {
      activeMenu.value = 'devices'
      currentDeviceId.value = null
    }
    
    // 检查登录状态
    const savedLoginState = localStorage.getItem('isLoggedIn')
    const savedGuestMode = localStorage.getItem('isGuestMode')
    if (savedLoginState === 'true') {
      isLoggedIn.value = true
      isGuestMode.value = savedGuestMode === 'true'
    } else {
      isLoggedIn.value = false
      isGuestMode.value = false
    }

    onMounted(async () => {
      window.addEventListener('resize', handleResize)
      // 自动token登录
      let token = null
      if (window.location.hash.includes('?')) {
        const params = new URLSearchParams(window.location.hash.split('?')[1])
        token = params.get('token')
      }
      if (!token) {
        token = localStorage.getItem('sessionToken')
      }
      if (token) {
        try {
          await AV.User.become(token)
          localStorage.setItem('sessionToken', token)
        } catch (e) {
          localStorage.removeItem('sessionToken')
        }
      }
      // 支持扫码/URL直达设备详情页
      const hash = window.location.hash
      if (hash.startsWith('#/device-detail')) {
        const params = new URLSearchParams(hash.split('?')[1] || '')
        const id = params.get('id')
        if (id) {
          activeMenu.value = 'device-detail'
          currentDeviceId.value = id
        }
      }
      // 移除自动同步userRole逻辑，userRole只在login成功后赋值
      updateActiveMenu(route)
    })

    watch(() => route.path, (newPath, oldPath) => {
      updateActiveMenu(route)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      isLoggedIn,
      isGuestMode,
      showAdminLogin,
      password,
      activeMenu,
      currentComponent,
      currentDeviceId,
      login,
      loginAsGuest,
      logout,
      handleMenuSelect,
      goDetail,
      handleDeviceBack,
      drawerVisible,
      isMobile,
      userRole,
      userRoleLabel,
      currentUsername,
      appVersion
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: 
    radial-gradient(circle at 30% 70%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 70% 30%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
  animation: float 20s ease-in-out infinite;
  pointer-events: none;
}

@keyframes float {
  0%, 100% { transform: translate(0, 0) rotate(0deg); }
  25% { transform: translate(-10px, -10px) rotate(1deg); }
  50% { transform: translate(10px, -5px) rotate(-1deg); }
  75% { transform: translate(-5px, 10px) rotate(1deg); }
}

.login-box {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 400px;
  width: 100%;
}

.login-box h2 {
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
}

.login-options {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.app-container {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  background: #1f2937 !important;
  color: #fff;
  min-height: 100vh;
  box-shadow: 2px 0 12px 0 rgba(0,0,0,0.1);
  width: 250px;
  display: flex;
  flex-direction: column;
}

.dev-info {
  padding: 20px;
  border-bottom: 1px solid rgba(255,255,255,0.1);
}

.dev-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: 600;
}

.dev-info p {
  margin: 0;
  font-size: 12px;
}

.el-menu {
  background: transparent !important;
  color: #fff;
  border: none;
  padding-top: 18px;
  flex: 1;
}

.el-menu-item {
  background: rgba(255,255,255,0.02) !important;
  color: #d1d5db !important;
  transition: background 0.2s, color 0.2s, box-shadow 0.2s, border-radius 0.2s;
  border-radius: 8px;
  margin: 6px 10px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 1px 4px 0 rgba(0,0,0,0.05);
  border: 1.5px solid transparent;
}

.el-menu-item.is-active {
  background: #1677ff !important;
  color: #fff !important;
  box-shadow: 0 2px 8px 0 rgba(22,119,255,0.2);
  border-radius: 10px;
  border: 1.5px solid #1677ff;
}

.el-menu-item:hover {
  background: #1677ff !important;
  color: #fff !important;
  box-shadow: 0 2px 8px 0 rgba(22,119,255,0.25);
  border-radius: 10px;
  border: 1.5px solid #1677ff;
}

.el-menu-item:not(:last-child) {
  border-bottom: 1px solid rgba(255,255,255,0.05);
}

.logout-section {
  padding: 20px;
  border-top: 1px solid rgba(255,255,255,0.1);
}
.logout-section .el-button[link] {
  background: #f56c6c;
  color: #fff !important;
  border-radius: 8px;
  width: 100%;
  text-align: left;
  padding: 12px 20px;
  font-weight: bold;
  transition: background 0.2s;
}
.logout-section .el-button[link]:hover {
  background: #d93026;
  color: #fff !important;
}

.main-content {
  flex: 1;
  background: #f5f5f5;
  overflow-y: auto;
}

.project-title {
  text-align: left;
  margin: 10px 0 12px 0;
  padding-left: 2px;
  line-height: 0.85;
}
.project-title-main {
  font-size: 20px;
  font-weight: 700;
  color: #fff;
  letter-spacing: 1.5px;
  text-shadow: 0 1px 4px rgba(0,0,0,0.10);
  display: block;
  margin-bottom: 0;
}
.project-title-sub {
  font-size: 20px;
  font-weight: 400;
  color: #b6d4fa;
  letter-spacing: 2px;
  margin-left: 0;
  display: block;
  margin-bottom: 0;
}
.project-title::after {
  content: '';
  display: block;
  margin: 4px 0 0 0;
  width: 32px;
  height: 2px;
  background: linear-gradient(90deg, #1677ff 0%, #b6d4fa 100%);
  border-radius: 1px;
  opacity: 0.18;
}

/* 用户角色/访客模式左对齐 */
.user-role-label {
  padding-left: 2px;
  text-align: left;
}

@media (max-width: 700px) {
  .sidebar {
    display: none !important;
  }
  .mobile-header {
    display: flex;
    align-items: center;
    background: #1f2937;
    color: #fff;
    padding: 10px 12px;
    font-size: 16px;
    font-weight: bold;
    letter-spacing: 1px;
    box-shadow: 0 2px 8px 0 rgba(0,0,0,0.08);
    position: sticky;
    top: 0;
    z-index: 1002;
    min-height: 48px;
  }
  .mobile-header .el-button {
    min-width: 44px;
    min-height: 44px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #1677ff;
    color: #fff;
    border: none;
    box-shadow: 0 2px 8px rgba(22,119,255,0.12);
  }
  .mobile-header .el-button:active {
    background: #409eff;
  }
  .mobile-title {
    flex: 1;
    text-align: left;
    font-size: 16px;
    font-weight: bold;
    color: #fff;
    letter-spacing: 1px;
    margin-left: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .el-drawer.mobile-drawer {
    background: #f7f8fa !important;
    border-top-right-radius: 16px;
    border-bottom-right-radius: 16px;
    box-shadow: 2px 0 16px 0 rgba(22,119,255,0.08);
    padding-top: 0;
  }
  .el-drawer.mobile-drawer .el-menu {
    background: transparent;
    border: none;
    margin-top: 12px;
  }
  .el-drawer.mobile-drawer .el-menu-item {
    margin: 6px 0;
    border-radius: 8px;
    font-size: 16px;
    padding: 10px 18px;
    transition: background 0.2s;
  }
  .el-drawer.mobile-drawer .el-menu-item.is-active {
    background: #1677ff !important;
    color: #fff !important;
  }
  .el-drawer.mobile-drawer .logout-section {
    margin-top: 18px;
    padding: 0 18px;
  }
  .el-drawer.mobile-drawer .dev-info {
    padding: 16px 18px 8px 18px;
    font-size: 12px;
    color: #888;
    text-align: left;
  }
  .dashboard-card {
    min-height: 120px;
    padding: 10px 4px 16px 4px;
    font-size: 14px;
  }
  .card-title {
    font-size: 15px;
    margin-bottom: 6px;
  }
  .card-value {
    font-size: 28px;
    margin-top: 8px;
  }
  .dashboard-table-card {
    margin-bottom: 12px;
    padding: 0 2px;
  }
  .el-table {
    font-size: 12px !important;
  }
  .el-table .cell {
    font-size: 12px !important;
    padding: 2px 4px !important;
  }
  .el-pagination {
    font-size: 12px !important;
    flex-wrap: wrap;
  }
  .el-button, .el-input, .el-select {
    font-size: 13px !important;
    min-width: 60px;
    margin-bottom: 4px;
  }
  .el-row, .el-col {
    flex-wrap: wrap !important;
  }
}
</style>